import React from 'react';
import moment from 'moment';
import { Form, Select, DatePicker, Button, message } from 'antd';
import Api from 'Utils/api';
import CREDIT_LEVEL from 'Constants/creditConstant';
import { connect } from 'react-redux';
import ChartOfCheckNum from './component/ChartOfCheckNum';
import ChartOfColumnar from './component/ChartOfColumnar';
import ChartOfThreeColumnar from './component/ChartOfThreeColumnar';
import './index.scss';

const FormItem = Form.Item;
const Option = Select.Option;
const dateFormat = 'YYYY-MM-DD';
const chartNum = 9;
const pageSize = 3;
class AnalyzePage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      areaId: '',
      startTime: '1900-01-01',
      endTime: '2017-12-06',
      areaData: [{
        id: '',
        name: '全部区域'
      }],
      regulatorData: [], // 监管机构检查次数分析
      businessTypeData: [], // 企业类型
      gpsData: [], //企业检查次数分析（永安通）
      recordData: [], // 企业检查次数分析（移动执法）
      creditData: [], //信用等级
      hisData: [], //巡检情况分析
      productData: [], //抽检情况分析
      riskData: [], //企业风险
      foodTypeData: [], //追溯系统分析,
      totalNum: chartNum,
      pageNum: Math.ceil(chartNum / pageSize),
      currentPage: 1,
      contentWidth: 0
    };
    this.initOrganise = ::this.initOrganise;
    this.changeDataName = ::this.changeDataName;
    this.changeContentWidth = ::this.changeContentWidth;
  }

  componentWillMount() {
    this.initOrganise();
    this.initData();
  }
  componentDidMount() {
    sessionStorage.setItem('normalWidth', document.getElementById('top').offsetWidth);
    this.changeContentWidth();
  }
  componentWillReceiveProps(nexProps) {
   // 侧边显示隐藏的时候右边内容区的宽度
    const norWidth = parseInt(sessionStorage.getItem('normalWidth'), 10);
    const changeWidth = document.getElementById('top').offsetWidth;
    if (nexProps.hideSide) {
      document.getElementById('chart-wrap').style.width = `${changeWidth}px`;
    } else {
      document.getElementById('chart-wrap').style.width = `${norWidth}px`;
    }
    this.changeContentWidth();
    this.changeSwiper();
  }
  changeContentWidth() {
    const { pageNum } = this.state;
    const wrapWidth = document.getElementById('top').offsetWidth;
    document.getElementById('chart-wrap').style.width = `${wrapWidth}px`;
    this.setState({
      contentWidth: wrapWidth * pageNum,
    });
  }
  initData() {
    this.initDataRegulator();
    this.initDataCategory();
    this.initGpsData();
    this.initRecordData();
    this.initCreditData();
    this.initProductData();
    this.initHisData();
    this.initRiskData();
    this.initFoodData();
  }
  // public for pie
  // 监管机构检查次数分析
  initDataRegulator() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/regulator',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        this.setState({
          regulatorData: this.changeDataName(res, true)
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  // 企业类型
  initDataCategory() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/category',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        this.setState({
          businessTypeData: this.changeDataName(res, false)
        });
      },
      error: (msg) => {
        message.error(`企业类型${msg}`);
      }
    });
    api.run();
  }
  // 企业检查次数分析（永安通）
  initGpsData() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/gps',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        this.setState({
          gpsData: res.length > 0 ? this.changeDataName(res, false) : []
        });
      },
      error: (msg) => {
        message.error(`企业检查次数分析（永安通）${msg}`);
      }
    });
    api.run();
  }
  // 企业检查次数分析（移动执法）
  initRecordData() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/record',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        this.setState({
          recordData: res.length > 0 ? this.changeDataName(res, false) : []
        });
      },
      error: (msg) => {
        message.error(`企业检查次数分析（移动执法）${msg}`);
      }
    });
    api.run();
  }
  // 信用等级分析
  initCreditData() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/credit',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        const countArr = res.length > 0 ? res.map(item => item.count) : [];
        const sum = this.getSum(countArr);
        const newData = [];
        for (let i = 0, len = res.length; i < len; i++) {
          const item = {
            name: this.getCreditLevel(res[i].keyword),
            value: parseFloat((res[i].count / sum).toFixed(4))
          };
          newData.push(item);
        }
        this.setState({
          creditData: [...newData]
        });
      },
      error: (msg) => {
        message.error(`信用等级分析${msg}`);
      }
    });
    api.run();
  }
  //追溯系统分析
  initFoodData() {
    const api = new Api({
      method: 'GET',
      path: '/analyze/food',
      success: (res) => {
        this.setState({
          foodTypeData: this.changeDataName(res, false)
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  //public for chart
  // 抽检情况分析
  initProductData() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/product',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        const newData = res.map((item, index) => {
          const sum = item.pass + item.unpass;
          const num1 = this.getCountResult(item.pass, sum);
          const num2 = this.getCountResult(item.unpass, sum);
          const newItem = {
            type: item.category || `${index + 1}`,
            num: num1,
            num2: [num1, num1 + num2],
          };
          return newItem;
        });
        this.setState({
          productData: newData
        });
      },
      error: (msg) => {
        message.error(`抽检情况分析${msg}`);
      }
    });
    api.run();
  }
  // 巡检情况分析
  initHisData() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/record/his',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        const newData = res.map((item, index) => {
          const sum = item.pass + item.unpass;
          const num1 = this.getCountResult(item.pass, sum);
          const num2 = this.getCountResult(item.unpass, sum);
          const newItem = {
            type: item.category || `${index + 1}`,
            num: num1,
            num2: [num1, num1 + num2],
          };
          return newItem;
        });
        this.setState({
          hisData: newData
        });
      },
      error: (msg) => {
        message.error(`巡检情况分析${msg}`);
      }
    });
    api.run();
  }
  // 企业风险
  initRiskData() {
    const { areaId, startTime, endTime } = this.state;
    const api = new Api({
      method: 'GET',
      path: '/analyze/risk',
      query: {
        govid: areaId ? parseInt(areaId, 10) : '',
        start_time: startTime,
        end_time: endTime
      },
      success: (res) => {
        const newData = res.map((item, index) => {
          const sum = item.level1 + item.level2 + item.level3 + item.level4;
          const num1 = this.getCountResult(item.level1, sum);
          const num2 = this.getCountResult(item.level2, sum);
          const num3 = this.getCountResult(item.level3, sum);
          const num4 = this.getCountResult(item.level4, sum);
          const newItem = {
            type: item.category || `${index + 1}`,
            num: num1,
            num2: [num1, num1 + num2],
            num3: [num1 + num2, num1 + num2 + num3],
            num4: [num1 + num2 + num3, num1 + num2 + num3 + num4]
          };
          return newItem;
        });
        this.setState({
          riskData: newData
        });
      },
      error: (msg) => {
        message.error(`企业风险${msg}`);
      }
    });
    api.run();
  }
  //百分比结果
  getCountResult(num, sum) {
    return sum !== 0 ? parseFloat(((num / sum) * 100).toFixed(2)) : 0;
  }
  getCreditLevel(num) {
    const level = parseInt(num, 10);
    if (level === CREDIT_LEVEL.CAUTION) {
      return '警示';
    }
    if (level === CREDIT_LEVEL.EARLY_WARN) {
      return '预警';
    }
    if (level === CREDIT_LEVEL.GIVE_WARN) {
      return '告警';
    }
    return '正常';
  }
  getSum(countArr) {
    let sum = 0;
    for (let i = 0; i < countArr.length; i++) {
      sum += countArr[i];
    }
    return sum;
  }
  changeDataName(data, filter = false) {
    // filter监管机构分析中需要根据id获取区域名字
    const { areaData } = this.state;
    const countArr = data.map(item => item.count);
    const sum = this.getSum(countArr);
    const newData = [];
    for (let i = 0, len = data.length; i < len; i++) {
      let item = {};
      if (filter) {
        const name = areaData.filter(filt => parseInt(filt.id, 10) === parseInt(data[i].keyword, 10));
        item = {
          name: name.length > 0 ? name[0].name : '',
          value: parseFloat((data[i].count / sum).toFixed(4))
        };
      } else {
        item = {
          name: data[i].keyword || '',
          value: parseFloat((data[i].count / sum).toFixed(4))
        };
      }
      newData.push(item);
    }
    return newData;
  }
  initOrganise() {
    const api = new Api({
      method: 'GET',
      path: '/justices/dept',
      success: (res) => {
        const { areaData } = this.state;
        this.setState({
          areaData: [...areaData, ...res]
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  renderOption() {
    const { areaData } = this.state;
    const nodeInfo = [];
    for (let i = 0, len = areaData.length; i < len; i++) {
      nodeInfo.push((
        <Option value={areaData[i].id.toString()} key={areaData[i].id}>{areaData[i].name}</Option>
      ));
    }
    return nodeInfo;
  }
  handleClick() {
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const formValue = this.props.form.getFieldsValue();
        this.setState({
          areaId: formValue.area,
          startTime: formValue.startTime ? moment(formValue.startTime.hours(0).minutes(0).seconds(0)).format(dateFormat) : '',
          endTime: formValue.endTime ? moment(formValue.endTime.hours(0).minutes(0).seconds(0)).format(dateFormat) : ''
        }, () => {
          this.initData();
        });
      }
    });
  }
  handlePre() {
    const { currentPage } = this.state;
    if (currentPage === 1) {
      return;
    }
    this.setState({
      currentPage: currentPage - 1
    }, () => {
      this.changeSwiper();
    });
  }
  handleNext() {
    const { currentPage, pageNum } = this.state;
    if (currentPage === pageNum) {
      return;
    }
    this.setState({
      currentPage: currentPage + 1
    }, () => {
      this.changeSwiper();
    });
  }
  onListPageChange(page) {
    this.setState({
      currentPage: page
    }, () => {
      this.changeSwiper();
    });
  }
  changeSwiper() {
    const { currentPage } = this.state;
    const wrapWidth = document.getElementById('top').offsetWidth;
    const eleSwiper = document.getElementById('swippers');
    eleSwiper.style.transform = `translateX(-${wrapWidth * (currentPage - 1)}px)`;
    eleSwiper.style.transition = '300ms';
  }
  renderFooter() {
    const { currentPage, pageNum } = this.state;
    const nodeInfo = [];
    for (let i = 0; i < pageNum; i++) {
      const currentClass = i + 1 === currentPage ? 'active-page' : 'normal-page';
      nodeInfo.push((
        <span key={i} className={currentClass} onClick={this.onListPageChange.bind(this, i + 1)} />
      ));
    }
    return nodeInfo;
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { totalNum, contentWidth, areaData, startTime, endTime, businessTypeData, regulatorData, gpsData, recordData, creditData, riskData, productData, hisData, foodTypeData } = this.state;
    const itemWidth = `${(contentWidth - ((totalNum - 1) * 20)) / totalNum}px`;
    return (
      <div className="analyze-page-container">
        <div className="search-action-wrap" id="top">
          <Form layout="inline">
            <FormItem>
              {getFieldDecorator('area', { initialValue: '' })(
                <Select style={{ width: 260 }}>
                  {
                    areaData.length > 0 ? this.renderOption() : ''
                  }
                </Select>
              )}
            </FormItem>
            <div className="label">
              开始时间：
            </div>
            <FormItem>
              {getFieldDecorator('startTime', {
                initialValue: moment(startTime, dateFormat),
                rules: [
                  { required: true, message: '请选择' }
                ]
              })(
                <DatePicker placeholder="请选择" />
              )}
            </FormItem>
            <div className="label">
              结束时间：
            </div>
            <FormItem>
              {getFieldDecorator('endTime', {
                initialValue: moment(endTime, dateFormat),
                rules: [
                  { required: true, message: '请选择' }
                ]
              })(
                <DatePicker placeholder="请选择" />
              )}
            </FormItem>
            <Button type="primary" className="search-btn" onClick={this.handleClick.bind(this)}>
              <img src="images/icon_analyze.png" alt="分析" />开始分析
            </Button>
          </Form>
        </div>
        <div className="charts-container" id="chart-wrap">
          <div className="swipper-wrap" id="swippers" style={{ width: `${contentWidth}px` }}>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">监管机构检查次数分析</div>
              <ChartOfCheckNum data={regulatorData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title" >企业类型分布</div>
              <ChartOfCheckNum data={businessTypeData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title" >企业检查次数分析(永安通)</div>
              <ChartOfCheckNum data={gpsData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">企业检查次数分析（移动执法）</div>
              <ChartOfCheckNum data={recordData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">抽检情况分析</div>
              <ChartOfColumnar data={productData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">巡检情况分析</div>
              <ChartOfColumnar data={hisData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">信用等级分析</div>
              <ChartOfCheckNum data={creditData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">企业风险分析</div>
              <ChartOfThreeColumnar data={riskData} />
            </div>
            <div className="chart-item" style={{ width: itemWidth }}>
              <div className="title">追溯记录统计</div>
              <ChartOfCheckNum data={foodTypeData} />
            </div>
          </div>
        </div>
        <div className="new-pagination-wrap">
          {
            totalNum > 0 ?
              <div>
                <div className="pre-btn" onClick={this.handlePre.bind(this)} />
                {this.renderFooter()}
                <div className="next-btn" onClick={this.handleNext.bind(this)} />
              </div>
              : ''
          }
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.mapReducer
  };
}

export default connect(mapStateToProps)(Form.create()(AnalyzePage));
